package work.thread_eg.concurrent.lock;

import java.util.Random;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 读写锁 （和数据库没关系）
 * 读线程：允许其他读进程   不允许写进程 共享锁
 * 写线程：不允许其他读进程 不允许写进程 排他锁
 *
 * 共享锁
 * 排他锁
 *
 */
public class ReadWriteLockTest01 {

    static Lock lock = new ReentrantLock();
    private  static int value;

    static ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
    static Lock readLock = readWriteLock.readLock();
    static Lock writeLock = readWriteLock.writeLock();

    public static void read(Lock lock) {
        try {
            lock.lock();
            Thread.sleep(1000);
            System.out.println("read over!");
            // 模拟读数据
        }catch (InterruptedException ex) {
            ex.printStackTrace();
        }finally {
            lock.unlock();
        }
    }
    public static void write(Lock lock, int v) {
        try {
            lock.lock();
            Thread.sleep(1000);
            value = v;
            System.out.println("write over!");
            // 模拟写数据
        }catch (InterruptedException ex) {
            ex.printStackTrace();
        }finally {
            lock.unlock();
        }
    }


    public static void main(String[] args) {
        // 如果读写进程都用的是一个ReentrantLock对象
        // 写进程都在等着 互斥锁 也就是派他锁
        // 读和写进程都是一秒一次 一共20秒
//        Runnable readR = ()-> read(lock);
//        Runnable writeR = ()-> write(lock,new Random().nextInt());

        // 使用同个ReentrantReadWriteLock的readLock 和 writeLock
        // 读锁是共享的 会一起执行 1秒全部读完
        // 写锁是排他的 一秒一次 一共3秒
        Runnable readR = ()-> read(readLock);
        Runnable writeR = ()-> write(writeLock,new Random().nextInt());

        for(int i = 0;i<18;i++) new Thread(readR).start();
        for(int i = 0;i<2;i++) new Thread(writeR).start();

    }
}
